package com.example.vendingmachine.controller;

import com.example.vendingmachine.dto.AreaDTO;
import com.example.vendingmachine.dto.AreaQuery;
import com.example.vendingmachine.entity.Area;
import com.example.vendingmachine.service.AreaService;
import com.example.vendingmachine.common.Result;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 区域管理控制器
 */
@RestController
@RequestMapping("/api/areas")
@RequiredArgsConstructor
public class AreaController {

    private final AreaService areaService;

    /**
     * 分页查询区域列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('area:list')")
    public Result<PageInfo<Area>> list(AreaQuery query) {
        return Result.success(areaService.listAreas(query));
    }

    /**
     * 获取区域详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('area:list')")
    public Result<Area> getInfo(@PathVariable Long id) {
        return Result.success(areaService.getAreaById(id));
    }

    /**
     * 新增区域
     */
    @PostMapping
    @PreAuthorize("hasAuthority('area:add')")
    public Result<Long> add(@Validated @RequestBody AreaDTO areaDTO) {
        return Result.success(areaService.createArea(areaDTO));
    }

    /**
     * 更新区域
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('area:edit')")
    public Result<Void> update(@PathVariable Long id, @Validated @RequestBody AreaDTO areaDTO) {
        areaDTO.setId(id);
        areaService.updateArea(areaDTO);
        return Result.success();
    }

    /**
     * 删除区域
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('area:delete')")
    public Result<Void> delete(@PathVariable Long id) {
        areaService.deleteArea(id);
        return Result.success();
    }

    /**
     * 更新区域状态
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('area:edit')")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestParam String status) {
        areaService.updateAreaStatus(id, status);
        return Result.success();
    }

    /**
     * 检查管理员是否可以被分配
     */
    @GetMapping("/check-admin")
    @PreAuthorize("hasAuthority('area:list')")
    public Result<Boolean> checkAdminAvailable(@RequestParam Long adminId) {
        return Result.success(areaService.checkAdminAvailable(adminId));
    }
} 